#include "pch.h"
#include "GLVertexArray.h"
#include <glad/glad.h>
namespace HS {

	static GLenum ShaderTypeToGLType(ShaderDataType type)
	{
		switch (type)
		{
		case ShaderDataType::None:		return GL_FLOAT;
		case ShaderDataType::Float:		return GL_FLOAT;
		case ShaderDataType::Float2:	return GL_FLOAT;
		case ShaderDataType::Float3:	return GL_FLOAT;
		case ShaderDataType::Float4:	return GL_FLOAT;
		case ShaderDataType::Mat3:		return GL_FLOAT;
		case ShaderDataType::Mat4:		return GL_FLOAT;
		case ShaderDataType::Int:		return GL_INT;
		case ShaderDataType::Int2:		return GL_INT;
		case ShaderDataType::Int3:		return GL_INT;
		case ShaderDataType::Int4:		return GL_INT;
		case ShaderDataType::Bool:		return GL_BOOL;
		}
		return 0;
	}


	GLVertexArray::GLVertexArray()
	{
		glCreateVertexArrays(1,&m_Handle);
	}

	GLVertexArray::~GLVertexArray()
	{
		glDeleteVertexArrays(1,&m_Handle);
	}

	void GLVertexArray::Bind() const
	{
		glBindVertexArray(m_Handle); 
	}

	void GLVertexArray::Unbind() const
	{
		glBindVertexArray(0);
	}

	void GLVertexArray::SetVertexBuffer(const std::shared_ptr<VertexBuffer>& vertexBuffer)
	{
		glBindVertexArray(m_Handle);
		vertexBuffer->Bind();

		uint32_t i = 0;
		for (const auto& e : vertexBuffer->GetLayout())
		{
			glEnableVertexAttribArray(i);
			glVertexAttribPointer(i, e.GetComponentCount(),
				ShaderTypeToGLType(e.Type),
				e.Normalized ? GL_TRUE : GL_FALSE,
				vertexBuffer->GetLayout().GetStride(),
				(const void*)e.Offset);
			i++;
		}

		m_VertexBuffers.push_back(vertexBuffer);
	}

	void GLVertexArray::SetIndexBuffer(const std::shared_ptr<IndexBuffer>& indexBuffer)
	{
		glBindVertexArray(m_Handle);
		indexBuffer->Bind();
		m_IndexBuffers = indexBuffer;
	}
	VertexArray* GLVertexArray::Create()
	{
		return new GLVertexArray();
	}
}